#include "tlog.h"

TLog::TLog(QObject *parent)
    : QObject{parent}
{
    dateTime = new QDateTime;
    thread = new QThread(this);
    this->moveToThread(thread);
    thread->start(QThread::IdlePriority);
    qDebug()<<"start thread:"<<thread->currentThreadId();
}

void TLog::on_saveLog(int cate,QString time,QString fileName,QString func,int line,QString info)
{
    QFile file;
    QString extractTo = QCoreApplication::applicationDirPath();
    QString dirName = QDir::cleanPath(extractTo+QDir::separator()+".."+QDir::separator()+"syslog");
    QDir dir(dirName);
    qDebug()<<dirName;
    qDebug()<<"thread:"<<thread->currentThreadId();

    if (!dir.exists())
    {
        if(!dir.mkdir(dirName))
        {
            qDebug()<<"日志目录创建失败";
            return;
        }
    }
    file.setFileName(dirName+QDir::separator()+"log"+dateTime->currentDateTime().toString("yyyyMMddhh")+".csv");
    if(!file.open(QIODevice::ExistingOnly|QIODevice::ReadWrite|QIODevice::Append))
    {
        if(!file.open(QIODevice::WriteOnly))
        {
            qDebug()<<"文件创建失败";
            file.close();
            return;
        }
        else
        {
            qDebug()<<"文件创建成功";
            file.write("类别,时间,文件名,函数名,行号,信息\r\n");
        }
    }

    QByteArray cateByte;
    switch(cate)
    {
        case 0:
            cateByte = "INFO";
        break;
        case 1:
            cateByte = "WARNING";
        break;
        case 2:
            cateByte = "ERROR";
        break;
    default:
        cateByte = "INFO";
        break;
    }
    qDebug()<<cateByte<<fileName<<line;
    file.write(cateByte+",");
    file.write(time.toLocal8Bit()+",");
    file.write(fileName.toLocal8Bit()+",");
    file.write(func.toLocal8Bit()+",");
    file.write(QString("%1").arg(line).toLocal8Bit()+",");
    file.write(info.toLocal8Bit()+"\r\n");
    file.close();
}
